package impexp.importfile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONObject;

import com.aote.sql.SqlMapper;

public class XMLConfigAnaly implements IDataAnaly {

	private String xmlpath;

	@Override
	public JSONArray analy(List<String[]> data) {

		JSONArray result = new JSONArray();
		// 获取表头
		String[] headers = data.get(0);

		for (int i = 1; i < data.size(); i++) {
			JSONObject jsonObject = new JSONObject();
			for (int j = 0; j < data.get(i).length; j++) {
				jsonObject.put(loadMap().get(headers[j]), data.get(i)[j]);
			}
			result.put(jsonObject);
		}
		System.out.println(result);
		return result;
	}

	private Map<String, String> loadMap() {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		InputStream input = SqlMapper.class.getClassLoader()
				.getResourceAsStream(xmlpath);
		try {
			Document document = reader.read(input);
			Element root = document.getRootElement();
			for (Iterator it = root.elementIterator("column"); it.hasNext();) {
				Element elm = (Element) it.next();
				String property = elm.attribute("property").getValue();
				String Name = elm.attribute("Name").getValue();
				map.put(Name, property);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return map;
	}

	public String getXmlpath() {
		return xmlpath;
	}

	public void setXmlpath(String xmlpath) {
		this.xmlpath = xmlpath;
	}

}
